package com.moju.controller;

import com.moju.common.Constant;
import com.moju.common.Pagination;
import com.moju.pojo.Brand;
import com.moju.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/brand")
@SessionAttributes({"pager","brand"})
public class BrandController {

    @Autowired
    private BrandService brandService;

    @RequestMapping("/deleteBrandsByIds")
    public String deleteBrandsByIds(String ids){

        String[] split = ids.split(",");

        List<Object> list = new ArrayList<>();

        for (String s : split) {
            list.add(s);
        }

        brandService.deletesBrandsByIds(list);

        return "redirect:/brand/list";
    }


    @RequestMapping("/relUpdate")
    public String relUpdate(Brand brand){

        int i = brandService.updateBrandById(brand);

        return "redirect:/brand/list";
    }

    @RequestMapping("/getBrandById")
    public String getBrandById(Integer id,Model model){

        Brand brand = brandService.getBrandById(id);

        model.addAttribute("brand",brand);

        return "brand/edit";
    }


    @RequestMapping("/relAdd")
    public String relAdd(Brand brand){

        System.out.println(brand);

        int i = brandService.insertBrand(brand);

        return "redirect:/brand/list";
    }


    @RequestMapping("/toAddPage")
    public String toAddPage(){
        return "brand/add";
    }


    @RequestMapping("/deleteBrandById")
    public String deleteBrandById(Integer id){


        int i = brandService.deleteBrandById(id);


        return "redirect:/brand/list";
    }


    @RequestMapping("/list")
    public String getBrandList(@RequestParam(value = "name",required = false) String brandName,
                               @RequestParam(value = "isDisplay",defaultValue = "1") Integer isDisplay,
                               @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                               Model model){

        Pagination pager = brandService.getBrandByLikeAndDisplayWithLimit(brandName, isDisplay, pageNo, Constant.PAGE_SIZE);

        model.addAttribute("pager",pager);

        if(brandName!=null && !"".equals(brandName)){
            model.addAttribute("name",brandName);
        }

        model.addAttribute("isDisplay",isDisplay);

        return "brand/list";
    }


}
